<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习分析 - 在线学习平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .chart-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }
        .analysis-card {
            background: white;
            border-radius: 10px;
            padding: 25px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }
        .data-table {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
        }
        .progress {
            height: 25px;
            margin-bottom: 15px;
        }
        .btn-refresh {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            border: none;
            transition: transform 0.3s;
        }
        .btn-refresh:hover {
            transform: translateY(-2px);
        }
        .module-name {
            font-weight: 600;
            color: #343a40;
        }
        .ai-insight {
            background-color: #e3f2fd;
            border-left: 4px solid #2196F3;
            padding: 15px;
            border-radius: 0 5px 5px 0;
            margin-top: 20px;
            white-space: pre-wrap;
        }
        .error-message {
            color: #dc3545;
            background-color: #f8d7da;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
            display: none;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <a href="/" class="text-xl font-bold text-blue-600">学习平台</a>

            <div class="flex items-center space-x-4">
                {% if user %}
                <span class="text-gray-700">欢迎, {{ user.name }}</span>
                <a href="/analytics" class="text-blue-600 font-medium">
                    <i class="fa fa-bar-chart mr-1"></i> 学习分析
                </a>
                <button id="logoutBtn" class="text-gray-600 hover:text-red-600">
                    <i class="fa fa-sign-out mr-1"></i> 退出登录
                </button>
                {% else %}
                <a href="/login" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
                    登录/注册
                </a>
                {% endif %}
            </div>
        </div>
    </nav>

    <div class="header text-center">
        <div class="container">
            <h1 class="display-5 fw-bold">课程模块完课率分析</h1>
            <p class="lead">基于千问AI的数据分析与可视化</p>
        </div>
    </div>

    <div class="container">
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3>完课率分布</h3>
                    <button id="refreshBtn" class="btn btn-refresh text-white">
                        <i class="bi bi-arrow-repeat"></i> 刷新数据
                    </button>
                </div>
                <div class="chart-container">
                    <img id="chartImg" src="{{ chart_url }}" alt="课程完课率柱状图" class="img-fluid">
                    <div id="chartError" class="error-message"></div>
                </div>
            </div>

            <div class="col-md-6">
                <h3 class="mb-3">详细数据</h3>
                <div class="data-table">
                    {% for module, data in course_data.items() %}
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="module-name">{{ module }}</span>
                            <span>{{ data.completion_rate }}%</span>
                        </div>
                        <div class="progress">
                           <div class="progress-bar"
                                role="progressbar"
                                style="width: {{ data.completion_rate|safe }}%; background-color: {% if data.completion_rate > 80 %}#4CAF50{% elif data.completion_rate > 60 %}#2196F3{% elif data.completion_rate > 40 %}#FFC107{% else %}#FF5722{% endif %};"
                                aria-valuenow="{{ data.completion_rate }}"
                                aria-valuemin="0"
                                aria-valuemax="100">
                            </div>
                        </div>
                        <div class="d-flex justify-content-between text-muted small">
                            <span>完成: {{ data.completed }}</span>
                            <span>总人数: {{ data.total_students }}</span>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <div class="analysis-card">
            <h3 class="mb-4">千问AI分析报告</h3>
            <div class="ai-insight" id="analysisContent">
                {{ analysis }}
            </div>
            <div id="analysisError" class="error-message"></div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-12 mt-16">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div>
                    <h3 class="text-xl font-bold mb-4">学习平台</h3>
                    <p class="text-gray-400">提供高质量的在线课程，帮助你掌握新技能，实现职业发展。</p>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">快速链接</h3>
                    <ul class="space-y-2 text-gray-400">
                        <li><a href="#" class="hover:text-white">关于我们</a></li>
                        <li><a href="#" class="hover:text-white">联系我们</a></li>
                        <li><a href="#" class="hover:text-white">常见问题</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">关注我们</h3>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-400 hover:text-white"><i class="fa fa-facebook"></i></a>
                        <a href="#" class="text-gray-400 hover:text-white"><i class="fa fa-twitter"></i></a>
                        <a href="#" class="text-gray-400 hover:text-white"><i class="fa fa-instagram"></i></a>
                        <a href="#" class="text-gray-400 hover:text-white"><i class="fa fa-linkedin"></i></a>
                    </div>
                </div>
            </div>
            <div class="border-t border-gray-700 mt-8 pt-8 text-center text-gray-500">
                <p>&copy; 2023 学习平台. 保留所有权利.</p>
            </div>
        </div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 登出功能
        document.getElementById('logoutBtn')?.addEventListener('click', function() {
            fetch('/logout')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = '/';
                    }
                });
        });

        // 设置后端API基础URL
        const API_BASE_URL = 'http://localhost:5000';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 如果初始数据加载失败，尝试重新获取
            if (!document.getElementById('chartImg').src.includes('base64')) {
                loadChart();
            }
        });

        // 加载图表数据
        async function loadChart() {
            try {
                const response = await fetch(`${API_BASE_URL}/api/completion-chart`);
                if (!response.ok) throw new Error('图表数据获取失败');

                const data = await response.json();
                document.getElementById('chartImg').src = data.chart;
                document.getElementById('chartError').style.display = 'none';
            } catch (error) {
                console.error('图表加载错误:', error);
                document.getElementById('chartError').textContent =
                    `图表加载失败: ${error.message}. 请确保后端服务正在运行并刷新页面。`;
                document.getElementById('chartError').style.display = 'block';
            }
        }

        // 加载分析报告
        async function loadAnalysis() {
            try {
                const response = await fetch(`${API_BASE_URL}/api/analysis`);
                if (!response.ok) throw new Error('分析报告获取失败');

                const data = await response.json();
                document.getElementById('analysisContent').textContent = data.analysis;
                document.getElementById('analysisError').style.display = 'none';
            } catch (error) {
                console.error('分析报告加载错误:', error);
                document.getElementById('analysisError').textContent =
                    `分析报告加载失败: ${error.message}. 请确保后端服务正在运行并刷新页面。`;
                document.getElementById('analysisError').style.display = 'block';
            }
        }

        // 刷新按钮事件
        document.getElementById('refreshBtn').addEventListener('click', async function() {
            const btn = this;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 分析中...';
            btn.disabled = true;

            try {
                // 刷新所有数据
                const refreshResponse = await fetch(`${API_BASE_URL}/refresh`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'}
                });

                if (!refreshResponse.ok) throw new Error('数据刷新失败');

                const data = await refreshResponse.json();

                // 更新图表
                document.getElementById('chartImg').src = data.chart_url;

                // 更新分析报告
                document.getElementById('analysisContent').textContent = data.analysis;

                // 更新详细数据
                const modules = Object.keys(data.course_data);
                modules.forEach((module, index) => {
                    const moduleData = data.course_data[module];
                    const progressBar = document.querySelectorAll('.progress-bar')[index];
                    const labels = document.querySelectorAll('.module-name')[index];
                    const values = document.querySelectorAll('.d-flex.justify-content-between span:last-child')[index];
                    const counts = document.querySelectorAll('.d-flex.justify-content-between.text-muted.small span');

                    // 更新模块名称和百分比
                    labels.textContent = module;
                    values.textContent = moduleData.completion_rate + '%';

                    // 更新进度条
                    progressBar.style.width = moduleData.completion_rate + '%';
                    progressBar.setAttribute('aria-valuenow', moduleData.completion_rate);

                    // 更新颜色
                    if (moduleData.completion_rate > 80) {
                        progressBar.style.backgroundColor = '#4CAF50';
                    } else if (moduleData.completion_rate > 60) {
                        progressBar.style.backgroundColor = '#2196F3';
                    } else if (moduleData.completion_rate > 40) {
                        progressBar.style.backgroundColor = '#FFC107';
                    } else {
                        progressBar.style.backgroundColor = '#FF5722';
                    }

                    // 更新人数数据
                    counts[index*2].textContent = '完成: ' + moduleData.completed;
                    counts[index*2+1].textContent = '总人数: ' + moduleData.total_students;
                });

                // 隐藏错误信息
                document.getElementById('chartError').style.display = 'none';
                document.getElementById('analysisError').style.display = 'none';

            } catch (error) {
                console.error('刷新错误:', error);
                document.getElementById('chartError').textContent =
                    `数据刷新失败: ${error.message}. 请检查后端服务状态。`;
                document.getElementById('chartError').style.display = 'block';
            } finally {
                // 恢复按钮状态
                btn.innerHTML = '<i class="bi bi-arrow-repeat"></i> 刷新数据';
                btn.disabled = false;
            }
        });
    </script>
</body>
</html>
